package com.jmu.medicineknows.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jmu.medicineknows.dto.MenuQueryDto;
import com.jmu.medicineknows.entity.Menu;
import com.jmu.medicineknows.entity.Result;
import com.jmu.medicineknows.entity.RoleMenu;
import com.jmu.medicineknows.mapper.MenuMapper;
import com.jmu.medicineknows.service.MenuService;
import com.jmu.medicineknows.utils.MenuUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: JieZi
 * @Date: 2023/7/11 23:39
 * @Description:
 **/
@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuMapper;

    @Override
    public Result list(MenuQueryDto dto) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        if(dto.title != null){
            queryWrapper.like(Menu::getTitle,dto.getTitle());
        }
        IPage<Menu> page = new Page<>(dto.currentPage, dto.pageSize);
        IPage<Menu> pages = menuMapper.selectPage(page, queryWrapper);
        List<Menu> menus = MenuUtil.generateMenu(pages.getRecords());
        pages.setRecords(menus);
        return Result.defaultSuccess(pages);
    }

    @Override
    public Result delete(Long id) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getId, id);
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setMenuId(id);
        menuMapper.deleteRoleMenu(roleMenu);
        return Result.defaultSuccess(menuMapper.delete(queryWrapper));
    }

    @Override
    public Result update(Menu menu) {
        if (menu.getId() != null) {
            UpdateWrapper<Menu> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", menu.getId());
            return Result.defaultSuccess(menuMapper.update(menu, updateWrapper));
        } else {
            Long pid = menu.getParentId();
            if(pid != 0){
                LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Menu::getParentId,pid);
                Menu selectOne = menuMapper.selectOne(queryWrapper);
                if(selectOne == null){
                    return Result.failure(405,"父菜单id不存在");
                }
            }
            return Result.defaultSuccess(menuMapper.insert(menu));
        }
    }
    @Override
    public Result ids() {
        return Result.defaultSuccess(menuMapper.selectList(null).stream().map(Menu::getId));
    }
}